var runningId = 1;
var genes_string = "";
var generator_state_string = "";
var footprint_length = 0;
var footprint_width = 13.0;
var facadeSize = new Array();
facadeSize[0] = 1.2
var GeneratorIsRunning = false;
var spacingMin = 3.0;//facadeSize < footprint_length ? facadeSize : footprint_length;
var spacingMax = 15.0;//footprint_length;
var spacingSetp = 0.5;
var zoneMin = 0.0;
var zoneMax = 0.0;
// var zoneV1 = 0.0;
// var zoneV2 = 0.0;
var zoneStep = 0.1;
var clzn_rLoaded = false;
function onLoad(){
}

function callRubyUpdateTimeMessage(actionName){
    window.location.href = 'skp:update_time_message@' + actionName;
}
function callRubySketchupExit(){
    query = 'skp:sketchup_exit@';
    window.location.href = query;
}
function callRubyReadDataBase(){
    query = 'skp:read_database@';
    window.location.href = query;
}
function callRubySetConfigurationValues(){
    query = 'skp:update_configurations@';
    window.location.href = query;
}
function callRubyRunGenerator(){
    query = 'skp:run_generator@';
    window.location.href = query;
}
function callRubyShowStructure(){
    query = 'skp:show_structure@';
    window.location.href = query;
}
function fromRb_UpdateTimeIcon(value) {
    var runningIcon = document.getElementById('runningIcon');
    runningIcon.setAttribute("src", "24/running_" + runningId + ".png");
    runningId += 1;
    if (runningId > 8) {
        runningId = 1;
    }
}
function fromRb_UpdateTimeIconById(value) {
    var runningIcon = document.getElementById('runningIcon');
    runningId = value%9;
    runningIcon.setAttribute("src", "24/running_" + runningId + ".png");
}
function fromRb_UpdateTimeMessage(value) {
    document.getElementById('timerOutput').innerHTML = value;
}
function fp_width_changed (argument) {

    window.location.href = 'skp:log_rb@' + "footprint_width: " + footprint_width;
    var min = Math.ceil(footprint_width.toFixed(0)/350)*0.1;
    var max = Math.floor(footprint_width/2)/1000.0;
    $("#clzn_rRangeSlider").slider( "option", "min", min );
    $("#clzn_rRangeSlider").slider( "option", "max", max );
    var v1 = $("#clzn_rRangeSlider").slider( "option", "values" )[0];
    var v2 = $("#clzn_rRangeSlider").slider( "option", "values" )[1];
    window.location.href = 'skp:log_rb@' + "min:" + min  + " ;  max:" + max + " ;  v1:" + v1+ " ;  v2:" + v2;
    window.location.href = 'skp:log_rb@' + "clzn_rLoaded: " + clzn_rLoaded;
    window.location.href = 'skp:log_rb@' + "v1: " + v1;
    window.location.href = 'skp:log_rb@' + "v2: " + v2;
    if ( clzn_rLoaded && ( !( v1 > min && v1 < max && v2 > min && v2 < max && v1 > zoneStep)  || ( v1 == 0 && v2 == 0 ) ) ) {
        $("#clzn_rRangeSlider").slider( "option", "values", [ Math.round(footprint_width*0.4)/1000.0,  Math.round(footprint_width*0.4)/1000.0] );
    };
    window.location.href = 'skp:log_rb@' + "min:" + min  + " ;  max:" + max + " ;  v1:" + v1+ " ;  v2:" + v2;
    // $("#clzn_rRangeSlider").slider( "option", "values", [ Math.round(footprint_width*0.4)/1000.0,  Math.round(footprint_width*0.4)/1000.0] );
}
function fp_length_changed (argument) {
    refreshColSpansSel()
}
function fromRb_SetValue(elementId, valStr){
    var valArr = valStr.split(",");
    switch(elementId){
        case "#fp_wdtValue":
            footprint_width = valArr[0]*1000
            fp_width_changed()
            break;
        case "#fp_lngValue":
            footprint_length = valArr[0]*1000
            fp_length_changed()
            break;
        default:
                break;
    }
}
function fromRb_SetSlider(elementId, valStr){
    var valArr = valStr.split(",");
    $(elementId).slider( "value", valArr[0] );
}
function fromRb_SetRangeSlider(elementId, valStr){
    var valArr = valStr.split(",");
    var v1 = valArr[0];
    var v2 = valArr[1];
    var min = $(elementId).slider( "option", "min");
    var max = $(elementId).slider( "option", "max");
    if ( v1 > min && v1 < max && v2 > min && v2 < max && v1 > zoneStep) {
        $(elementId).slider( "option", "values", [valArr[0], valArr[1]] );
    }
    else{
        // $(elementId).slider( "option", "values", [ Math.round(footprint_width*0.4)/1000.0,  Math.round(footprint_width*0.4)/1000.0] );
    }
    if ( "#clzn_rRangeSlider" == elementId) { clzn_rLoaded = true; fp_width_changed();};
}
function fromRb_SetMultiSelect(elementId, valStr){
    var valArr = valStr.split(",");
    $(elementId).multiselect("uncheckAll");
    i = 0, size = valArr.length;
    for(i; i < size; i++){
      $(elementId).multiselect("widget").find(":checkbox[value='"+valArr[i]+"']").attr("checked","checked");
      $(elementId+" option[value='" + valArr[i] + "']").attr("selected", 1);
    }
    $(elementId).multiselect("refresh");
    $(elementId).multiselect("open");
    $(elementId).multiselect("close");
}
function fromRb_SetWebUi (elementId, arg) {
     switch(elementId){
        case "set_open_div":
            if (arg) { $("#configurations").show();}
            else{ $("#configurations").hide();}
            break;
        case "S1":
            break;
        default:
                break;
    }

}
function refreshColSpansSel(){
    var colSpansSel = document.getElementById('cl_spsMultiSelect');
    var facadeSel = document.getElementById('fd_wdtMultiSelect');
    //var
     // facadeSize = Math.round(facadeSel.options[facadeSel.selectedIndex].value*1000);
     // facadeSize = 
    var columnSpacingRangeSlider = $("#clsp_rRangeSlider");
    var minSpanLength = columnSpacingRangeSlider.slider( "values", 0 )*1000;
    var maxSpanLength = columnSpacingRangeSlider.slider( "values", 1 )*1000;
    var mySpanAry=new Array();

    for (var i = facadeSize.length - 1; i >= 0; i--) {
        facadeWidth = facadeSize[i]*1000;
        spanLength = facadeWidth;
        if( spanLength != 0 && footprint_length != 0)
        {
            while ( spanLength < minSpanLength)
            {
                spanLength += facadeWidth;
            }
        //     window.location.href = 'skp:log_rb@' + "spanLength:" + spanLength;
        // window.location.href = 'skp:log_rb@' + "footprint_length:" + footprint_length;
        // window.location.href = 'skp:log_rb@' + "footprint_length%spanLength:" + footprint_length%spanLength;
            while ( spanLength < maxSpanLength)
            {
                spanLength += facadeWidth;
                if( footprint_length % spanLength == 0)
                {
                    spacing = footprint_length / spanLength
                    if ( -1 == $.inArray(spacing, mySpanAry) )
                    {
                        mySpanAry.push(spacing);
                    }
                }
            }
        }
    };

    if( footprint_length != 0)
    {
        // mySpanAry.reverse();
        mySpanAry.sort();
        
        colSpansSel.remove(0);
        for(i=colSpansSel.length-1; i>=0; i--)
        {
            colSpansSel.remove(i);
        }
        if( mySpanAry.length == 0)
        {
            var option = document.createElement('option');
            option.text = "--";
            option.value = "--";
            option.disabled = "disabled";
            try
            {
                // for IE earlier than version 8
                colSpansSel.add(option,colSpansSel.options[null]);
            }
            catch (e)
            {
                colSpansSel.add(option,null);
            }
        }
        else 
        {
            for(i=0; i<mySpanAry.length; i++)
            {
                var option = document.createElement('option');
                option.text = "" + mySpanAry[i] + "  x  " + (footprint_length / mySpanAry[i]) + "mm";
                option.value = mySpanAry[i];
                try
                {
                    // for IE earlier than version 8
                    colSpansSel.add(option,colSpansSel.options[null]);
                }
                catch (e)
                {
                    colSpansSel.add(option,null);
                }
            }
        }
        $("select#cl_spsMultiSelect").multiselect('refresh');
        $("select#cl_spsMultiSelect").multiselect('checkAll');
//     query = 'skp:on_change_variables_array_float@' + "cl_sps"+","+spansArray;
        window.location.href = 'skp:on_change_var@' 
        + "cl_sps"+","+mySpanAry;
        $('.ui-multiselect').css('width', '100%');
    }
    
}
function setValueSlider(elementId, value){
    $( elementId ).slider( "value", value );
}
function setSliderRangeValue(elementId, valueMin, valueMax){
    $(elementId).slider( "option", "values", [valueMin, valueMax] );
}
function setValueMultiSelect(elementId, valArr){
    $(elementId).multiselect("uncheckAll");
    i = 0, size = valArr.length;
    for(i; i < size; i++){
      $(elementId).multiselect("widget").find(":checkbox[value='"+valArr[i]+"']").attr("checked","checked");
      $(elementId+" option[value='" + valArr[i] + "']").attr("selected", 1);
    }
    $(elementId).multiselect("refresh");
    $(elementId).multiselect("open");
    $(elementId).multiselect("close");
}
function setMultiSelectCheckAll(elementId){
    $(elementId).multiselect("checkAll");
    $(elementId).multiselect("refresh");
    $(elementId).multiselect("open");
    $(elementId).multiselect("close");
}
function setDefaultConfiguration(){
    setValueSlider("#p_sizeSlider", 500);
    setValueSlider("#nof_gnSlider", 1200);
    setValueSlider("#p_mutaSlider", 0.05);
    setValueSlider("#p_crssSlider", 0.95);
    setSliderRangeValue("#clsp_rRangeSlider", 2,10);
    setValueMultiSelect("#co_hghMultiSelect", [600]);
    setValueMultiSelect("#n_rowsMultiSelect", [1]);
    setValueMultiSelect("#dirctsMultiSelect", [0,1]);
    setValueMultiSelect("#fd_wdtMultiSelect", [1.2]);
    setSliderRangeValue("#clzn_rRangeSlider", 
        Math.round(footprint_width*0.4), 
        Math.round(footprint_width*0.4));
    refreshColSpansSel();
    $('.ui-multiselect').css('width', '100%');
    // window.location.href = 'skp:default_configuration@'

}
$(function() {
    var warning = $(".message");
    $("select#dirctsMultiSelect").multiselect({
        header: false,
        selectedList: 2,
        click: function(e){
            if( $(this).multiselect("widget").find("input:checked").length < 1 ){
                warning.addClass("error").removeClass("success").html(
                    "You need to check at least one direction!");
                return false;
            } else {
                warning.addClass("success").removeClass("error").html(
                    "Check box/-es.");
            }
        },
        close: function(){
            window.location.href = 'skp:on_change_var@' + 
            "dircts"+ "," + $(this).val();
        }
    });
    $("select#fd_wdtMultiSelect").multiselect({
        // multiple: false,
        header: false,
        noneSelectedText: "Select an Option",
        selectedList: 1,
        click: function(e){
            if( $(this).multiselect("widget").find("input:checked").length < 1 ){
                warning.addClass("error").removeClass("success").html(
                    "You need to check at least one facade width!");
                return false;
            } else {
                warning.addClass("success").removeClass("error").html(
                    "Check box/-es.");
            }
        },
        close: function(event, ui){
             facadeSize = $(this).val();
            refreshColSpansSel();
            // var facadeSel = document.getElementById('fd_wdtMultiSelect');
             // facadeSize = facadeSel.options[facadeSel.selectedIndex].value;
            window.location.href = 'skp:on_change_var@' 
            + "fd_wdt" + "," +facadeSize;;
        }
    });
    $("select#cl_spsMultiSelect").multiselect({
        selectedText: function(numChecked, numTotal, checkedItems){
            var msg = "";
            if( checkedItems.length == 0)
            {
                return ;
            }
            msg += checkedItems[0].value;
            for (i= 1; i<checkedItems.length && i < 4; i++)
            {
                msg +=  ", " + checkedItems[i].value;
            }
            if( checkedItems.length > 4)
            {
                return msg + ", ...";
            }
            return msg;
        },
        close: function(){  
            window.location.href = 'skp:on_change_var@' + 
            "cl_sps"+ "," + $(this).val();
        }
    });
    $( "#co_hghSlider" ).slider({
        orientation: "horizontal",
        min: 300,
        max: 1000,
        step: 50,
        value: 400,
        slide: function (event, ui) {
            $( "#valueConstructionHeight" ).text("Max Construction Height: "+ui.value + "mm");
        },
        change: function (event, ui) {
            $( "#valueConstructionHeight" ).text("Max Construction Height: "+ui.value + "mm");
            window.location.href = 'skp:on_change_var@'
            + "co_hgh" + ","+ui.value;
        }
    });
    $( "#p_sizeSlider" ).slider({
        orientation: "horizontal",
        min: 200,
        max: 2000,
        step: 200,
        value: 800,
        slide: function (event, ui) {
            $( "#valuePopulationSize" ).text("Populaion Size: "+ui.value);
        },
        change: function (event, ui) {
            $( "#valuePopulationSize" ).text("Populaion Size: "+ui.value);
            window.location.href = 'skp:on_change_var@'
            + "p_size" + ","+ui.value;
        }
    });
    $( "#nof_gnSlider" ).slider({
        orientation: "horizontal",
        min: 400,
        max: 4000,
        step: 200,
        value: 1500,
        slide: function (event, ui) {
            $( "#valueNofGenerations" ).text("Number of Generations: "+ui.value);
        },
        change: function (event, ui) {
            $( "#valueNofGenerations" ).text("Number of Generations: "+ui.value);
            window.location.href = 'skp:on_change_var@'
            + "nof_gn" + ","+ui.value;
        }
    });
    $( "#p_mutaSlider" ).slider({
        orientation: "horizontal",
        min: 0.00,
        max: 0.30,
        step: 0.025,
        value: 0.05,
        slide: function (event, ui) {
            $( "#valueMutProb" ).text("Mutation Probability: "+ui.value);
        },
        change: function (event, ui) {
            $( "#valueMutProb" ).text("Mutation Probability: "+ui.value);
            window.location.href = 'skp:on_change_var@'
            + "p_muta" + ","+ui.value;
        }
    });
    $( "#p_crssSlider" ).slider({
        orientation: "horizontal",
        min: 0.70,
        max: 1.00,
        step: 0.025,
        value: 0.95,
        slide: function (event, ui) {
            $( "#valueCrossProb" ).text("Crossover Probability: "+ui.value);
        },
        change: function (event, ui) {
            $( "#valueCrossProb" ).text("Crossover Probability: "+ui.value);
            window.location.href = 'skp:on_change_var@'
            + "p_crss" + ","+ui.value;
        }
    });
    $( "#clzn_rRangeSlider" ).slider({
        range: true,
        min: zoneMin,
        max: zoneMax,
        step: zoneStep,
        values: [ zoneMin, zoneMax],
        slide: function( event, ui ) {
            $( "#valueColumnZone" ).text( "Inner Column Position: " 
                + (ui.values[0]/1.0).toFixed(1) + "-" 
                + (ui.values[1]/1.0).toFixed(1) +"m");
        },
        change: function( event, ui ) {
            $( "#valueColumnZone" ).text( "Inner Column Position: " 
                + (ui.values[0]/1.0).toFixed(1) + "-" 
                + (ui.values[1]/1.0).toFixed(1) +"m");
            window.location.href = 'skp:on_change_var@' 
            + "clzn_r"+ "," + (ui.values[0]/1.0).toFixed(1) +
                        "," + (ui.values[1]/1.0).toFixed(1);
        }
    });
    $( "#clsp_rRangeSlider" ).slider({
        // range: true,
        // min: Math.ceil(footprint_width.toFixed(0)/350)*100,
        // max: Math.floor(footprint_width/2),
        // step: 100,
        // values: [ Math.round(footprint_width*0.4), Math.round(footprint_width*0.4)],
        // slide: function( event, ui ) {
        //     $( "#valueColumnZone" ).text( "Inner Column Position: " + (ui.values[0]/1000.0).toFixed(1) + "-" + (ui.values[1]/1000.0).toFixed(1) +"m");
        // },
        // change: function( event, ui ) {
        //     $( "#valueColumnZone" ).text( "Inner Column Position: " + (ui.values[0]/1000.0).toFixed(1) + "-" + (ui.values[1]/1000.0).toFixed(1) +"m");
        //     query = 'skp:set_column_zone_min@' + (ui.values[0]/1000.0).toFixed(1);
        //     window.location.href = query;
        //     query = 'skp:set_column_zone_max@' + (ui.values[1]/1000.0).toFixed(1);
        //     window.location.href = query;
        // }
        range: true,
        min: spacingMin,
        max: spacingMax,
        step: spacingSetp,
        values: [ spacingMin, spacingMax],
        slide: function( event, ui ) {
            $( "#valueColumnSpacingRange" ).text( "Column Spacing Range: " 
                + ui.values[0].toFixed(1) + "-" 
                + ui.values[1].toFixed(1) +"m");
        },
        change: function( event, ui ) {
            $( "#valueColumnSpacingRange" ).text( "Column Spacing Range: " 
                + (ui.values[0]).toFixed(1) + "-" 
                + (ui.values[1]).toFixed(1) +"m");
            window.location.href = 'skp:on_change_var@' 
            + "clsp_r"+ "," + (ui.values[0]).toFixed(1) +
                        ","+ (ui.values[1]).toFixed(1);
            refreshColSpansSel();
        }
    });
    $("#hideConfiguration").click(function () {
        if ( $("#configurations").is(":visible") ) {
            $("#configurations").hide();
            window.location.href = 'skp:on_change_ui@' 
            + "set_open_div"+ ", false";
        }else{
            $("#configurations").show();
            window.location.href = 'skp:on_change_ui@' 
            + "set_open_div"+ ", true";
        };
    });
    $("#configurations").hide();
    callRubyUpdateTimeMessage();
    callRubySetConfigurationValues();
    $('.ui-multiselect').css('width', '100%');
});